import datetime
import os
import threading
import tkinter as tk
from tkinter import ttk
from configparser import ConfigParser
import openpyxl
import tkcalendar
from tools_pmc import detect_date, lj_kcmxz, fill_blue


import babel.numbers


def button_click():
    # 创建一个新线程
    t = threading.Thread(target=show_selected_date)
    # 启动线程
    t.start()


def show_selected_date():
    btn.config(state=tk.DISABLED)
    selected_date_1 = cal1.get_date()
    selected_date_2 = cal2.get_date()
    cfg.set('set', 'date_old', str(selected_date_1))
    cfg.write(open(lj_config, "w"))
    time_1 = detect_date(selected_date_1, 1)
    time_2 = detect_date(selected_date_2, 1)
    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + '：取值时间段为' + time_1.strftime(
        "%Y/%m/%d") + "-" + time_2.strftime("%Y/%m/%d") + "\n")
    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + '：开始加载库存明细账\n')
    wb1 = openpyxl.load_workbook(lj_kcmxz)
    ws1 = wb1.worksheets[0]
    text.insert('end',
                str(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")) + '：库存明细账加载完成,处理中......\n')
    # noinspection PyGlobalUndefined
    a = 2

    for i in range(2, ws1.max_row + 1):
        if detect_date(ws1.cell(i, 5).value, 1).date() == time_1:
            a = i
            break

    list1 = [[], []]
    progressbar['maximum'] = ws1.max_row-a
    for i in range(a, ws1.max_row + 1):
        progressbar['value'] = i-a
        time_3 = detect_date(ws1.cell(i, 5).value, 1).date()
        if ws1.cell(i, 1).value[0:2] == "10" \
                and ws1.cell(i, 7).value == "原材料仓" \
                and ws1.cell(i, 2).value == "原材料" \
                and ws1.cell(i, 15).value == ("一般交易单" or "借出单") \
                and time_2 >= time_3 >= time_1:
            if ws1.cell(i, 1).value in list1[0]:
                list1[1][list1[0].index(ws1.cell(i, 1).value)] += ws1.cell(i, 13).value
            else:
                list1[0].append(ws1.cell(i, 1).value)
                list1[1].append(ws1.cell(i, 13).value)
    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：处理完成，正在导出......\n")
    wb = openpyxl.Workbook()
    ws = wb.worksheets[0]
    for i in range(0, len(list1[0])):
        ws.cell(i + 3, 1).value = list1[0][i]
        ws.cell(i + 3, 2).value = list1[1][i]
        ws.cell(i + 3, 1).data_type = "int"
        ws.cell(i + 3, 1).number_format = "0"
    ws.cell(1, 1).value = time_1.strftime("%Y/%m/%d") + "-" + time_2.strftime(
        "%Y/%m/%d") + "原材料仓一般交易单+借出单出库数量合计"
    ws.cell(2, 1).value = "品号"
    ws.cell(2, 2).value = "数量"
    ws.column_dimensions["A"].width = 15
    ws.column_dimensions["B"].width = 10
    ws.cell(2, 1).fill = fill_blue
    ws.cell(2, 2).fill = fill_blue
    ws.freeze_panes = 'A3'
    range_active = "A2:B" + str(ws.max_row)
    ws.auto_filter.ref = range_active

    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：完成！\n")

    desktop_path = os.path.join(os.environ['USERPROFILE'], 'Desktop')
    lj = desktop_path.replace('\\', "/") + "/" + "原材料出库.xlsx"
    try:
        wb.save(lj)
        text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：保存路径->" + lj + "\n")
    except PermissionError:
        text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + '：文件已打开，请关闭后重新运行！\n')
    try:
        # 调用系统的默认程序打开文件
        os.startfile(lj)
    except Exception:
        text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：无法打开文件:错误代码Exception\n")
    btn.config(state=tk.NORMAL)


root = tk.Tk()
root.title("原材料出库")
# root.geometry('600x200')
root.geometry("+750+400")
root.resizable(False, False)
# root.protocol("WM_DELETE_WINDOW", lambda: None)
# root.overrideredirect(True)


lj_config = "//192.168.70.101/19计划管理部/01.计划/1，数据处理工具/Tools/PMCtools_Python_v2.0/dist/config.ini"
cfg = ConfigParser()
cfg.read(lj_config)
date_old = cfg.get('set', 'date_old')
m = detect_date(date_old, 1).month
d = detect_date(date_old, 1).day

frame = tk.Frame(root)
frame.pack(side="top", anchor="nw")

frame_l = tk.Frame(frame)  # 第二层frame，左frame，长在主frame上
frame_r = tk.Frame(frame)  # 第二层frame，右frame，长在主frame上
frame_l.pack(side='left')
frame_r.pack(side='right')

label1 = tk.Label(frame_l, text="起始日期选择:")
label1.pack(padx=5, pady=5, side="top", anchor="nw")
cal1 = tkcalendar.DateEntry(frame_r, width=12, background='darkblue', foreground='white', borderwidth=2,
                            date_pattern='yyyy/mm/dd',
                            day=d, month=m)
cal1.pack(padx=5, pady=5, side="top", anchor="nw")
label2 = tk.Label(frame_l, text="截至日期选择:")
label2.pack(padx=5, pady=5, side="top", anchor="nw")
cal2 = tkcalendar.DateEntry(frame_r, width=12, background='darkblue', foreground='white', borderwidth=2,
                            date_pattern='yyyy/mm/dd', )
cal2.pack(padx=5, pady=5, side="top", anchor="nw")
btn = ttk.Button(root, text="确认", command=button_click)
btn.pack(padx=5, pady=5, side="top", anchor="nw")
text = tk.Text(root, width=60, height=10)
text.pack(padx=5, pady=5)
progressbar = ttk.Progressbar(root, length=480)
progressbar.pack(padx=5, pady=5)
root.mainloop()
